package services.sysusers

import models.users._
import play.api.Logging
import play.api.libs.json.JsValue
import services.kingdee.{KingdeePostV1, KingdeePostV2}

import javax.inject.Inject
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, ExecutionContext, Future}

class KingdeeUsersService @Inject()(
                                     kdpost:KingdeePostV2,
                                     kingdeeUsersRepository: KingdeeUsersRepository
                                  )(implicit exec: ExecutionContext)
  extends Logging {

  def getDC() = {
    kdpost.getDataCenters()

  }
  def kdUserList(name: String = "", mobile: String = "", status: Int = -1, page: Int = 1, limit: Int = 10) = {
    kingdeeUsersRepository.userFindby(name = name, mobile = mobile, status = status, page = page, limit = limit)
  }

  def kdUserCheck(id: Long, acct_id: String, name: String, mobile: String, forbid_status: String, fAppGroup: String, status: Int) = {
    val user = KingdeeUser(id = id, acct_id = acct_id, name = name, mobile = mobile, forbid_status = forbid_status, fAppGroup = fAppGroup, status = status)
    kingdeeUsersRepository.findById(user.id).map { dbuser =>
      val op = if (dbuser.isEmpty) kingdeeUsersRepository.create(user)
      else {
        val utemp = dbuser.head
        utemp._4 match {
          case 0 => false
          case 1 => kingdeeUsersRepository.updateStatus(user.id, 2)
          case 9 => true
          case _ => {
            if (utemp._5.getOrElse(1)==1) {
              true
            } else {
              kingdeeUsersRepository.updateStatus(user.id, 0);
              false
            }
          }
        }
      }
      op match {
        case false => false;
        case _ => true
      }
    }
  }

  def kdUserDel(id: Long) = {
    kingdeeUsersRepository.updateDisable(id)
  }

  def kdUserUpdate(id: Long, accountId: Int, status: Int) = {
    logger.debug(s"gyUserUpdate:id=$id,accountId=$accountId,status=$status")

  }

  def kddcList(page: Int = 1, limit: Int = 10) = kingdeeUsersRepository.kddcList(page, limit)

  def kddcAll = Await.result(kingdeeUsersRepository.kddcAll(), Duration.Inf)

  def kddcAdd(data: JsValue) = {
    val address = (data \ "address").as[String]
    val id = (data \ "id").as[String]
    val name = (data \ "name").as[String]
    val pwd = (data \ "pwd").as[String]
    val test = if ((data \ "test").asOpt[String].getOrElse("").isEmpty) false else true
    val user = (data \ "user").as[String]
    KingdeeDataCenter(id = id, name = name, test = test)


    Future(1)
  }

  def kddcEdit(data: JsValue) = Future(1)

  def accountAll = Await.result(kingdeeUsersRepository.accountAll(), Duration.Inf).map(f => (f._1.getOrElse(0), f._2))

}
